package net.jueb.frameworkDemo.orm.mongodb.util;

import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
public class SpringMongoUtil extends MongoUtil{

	
	public static MongoDbFactory getDbFactory(String host,int port,String authDataBaseName,String dataBaseName,String user,String pwd,MongoClientOptions.Builder builder)
	{
		return new SimpleMongoDbFactory(buildClient(host, port, authDataBaseName, user, pwd, builder), dataBaseName);
	}
	
	public static MongoDbFactory getDbFactory(MongoClient client,String dataBaseName)
	{
		return new SimpleMongoDbFactory(client, dataBaseName);
	}
	
	/**
	 * 去掉_class字段的转换器
	 * @param factory
	 * @return
	 */
	public static MongoConverter getDefaultMongoConverter(MongoDbFactory factory) {

		DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
		MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, new MongoMappingContext());
		converter.setTypeMapper(new DefaultMongoTypeMapper(null));//去掉_class字段
		converter.afterPropertiesSet();
		return converter;
	}
	
	public static MongoTemplate getMongoTemp(MongoDbFactory mongoDbFactory)
	{
		return new MongoTemplate(mongoDbFactory);
	}
	
	public static MongoTemplate getMongoTemp(MongoDbFactory mongoDbFactory, MongoConverter mongoConverter)
	{
		return new MongoTemplate(mongoDbFactory,mongoConverter);
	}
}
